package cn.appsys.config;

import org.apache.commons.dbcp.BasicDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.*;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

@Configuration
@PropertySource("classpath:log4j.properties")
@EnableAspectJAutoProxy           //开启注解切面
@EnableTransactionManagement     //开启事务
@ComponentScan(value = {"cn.appsys.dao","cn.appsys.service"})
public class SpringConfig {
    @Bean
    public DataSource dataSource() {
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName("oracle.jdbc.OracleDriver");
        dataSource.setUrl("jdbc:oracle:thin:@localhost:1521:orcl");
        dataSource.setPassword("root");
        dataSource.setUsername("system");
        return dataSource;
    }


    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean() {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource());
        //设置别名
        sqlSessionFactoryBean.setTypeAliasesPackage("cn.appsys.pojo");
        return sqlSessionFactoryBean;
    }

    @Bean //配置mapper映射器
    public MapperScannerConfigurer myGetMapperScannerConfigurer() {
        MapperScannerConfigurer myMapperScannerConfigurer = new MapperScannerConfigurer();
        myMapperScannerConfigurer.setBasePackage("cn.appsys.dao");
        myMapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactoryBean");
        return myMapperScannerConfigurer;
    }

    @Bean //事务管理器
    public PlatformTransactionManager transactionManager() {
        PlatformTransactionManager platformTransactionManager = new DataSourceTransactionManager(dataSource());
        return platformTransactionManager;
    }

    @Bean //5.x以下的版本需要配置 才可使用el
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer =
                new PropertySourcesPlaceholderConfigurer();
        return propertySourcesPlaceholderConfigurer;
    }

}
